<template>
  <el-drawer
    size="75%"
    :title="drawer.title"
    :visible.sync="drawer.open"
    :direction="direction"
    :before-close="handleClose"
  >
    <el-form
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="120px"
      class="column-form"
      :style="{ overflow: 'auto', height: fromHeight + 'px' }"
    >
      <el-row :gutter="20">
        <el-col :span="16">
          <el-col :span="24">
            <el-form-item label="栏目名称" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入栏目名称"
                :maxlength="30"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="栏目副标题" prop="subTitle">
              <el-input
                v-model="formData.subTitle"
                placeholder="请输入栏目副标题"
                :maxlength="50"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏目编号" prop="number">
              <el-input
                v-model="formData.number"
                placeholder="请输入栏目编号"
                :maxlength="30"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文标题" prop="enTitle">
              <el-input
                v-model="formData.enTitle"
                placeholder="请输入英文标题"
                :maxlength="50"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="Seo关键字" prop="keyWord">
              <el-input
                v-model="formData.keyWord"
                type="textarea"
                placeholder="请输入Seo关键字"
                :maxlength="100"
                :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="Seo描述" prop="summary">
              <el-input
                v-model="formData.summary"
                type="textarea"
                placeholder="请输入Seo描述"
                :maxlength="100"
                :autosize="{ minRows: 3, maxRows: 3 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属上级" prop="parent">
            <el-cascader
              v-model="formData.parent"
              :options="parentIdOptions"
              :props="parentProps"
              :style="{ width: '100%' }"
              placeholder="请选择所属上级"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="栏目模板" prop="templateId">
            <el-select
              v-model="formData.templateId"
              placeholder="请选择栏目模板"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in templateIdOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传" prop="imgUrl">
            <el-upload
              ref="imgUrl"
              :file-list="imgUrlfileList"
              :action="imgUrlAction"
              :before-upload="imgUrlBeforeUpload"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="栏目状态" prop="status">
            <el-switch v-model="formData.status"></el-switch>
          </el-form-item>
          <el-form-item label="外链地址" prop="linkUrl">
            <el-input
              v-model="formData.linkUrl"
              placeholder="请输入外链地址"
              clearable
              :style="{ width: '100%' }"
            >
              <template slot="prepend">http</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="栏目内容" prop="content">
            <tinymce-editor v-model="formData.content"></tinymce-editor>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button
          type="primary"
          :loading="drawer.btnLoading"
          @click="submitForm"
        >
          保存栏目
        </el-button>
        <el-button type="warning" @click="close">返回上一步</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script>
  import { getList, add, update, getTempList } from '@/api/cms/column'
  import { changeTree } from '@/utils/treeTool'
  import { deepClone } from '@/utils/index'
  import TinymceEditor from '@/components/tinymce-editor/tinymce-editor'
  export default {
    name: 'CmsColumnModify',
    components: { TinymceEditor },
    data() {
      return {
        drawer: {
          open: false,
          title: '添加栏目',
          btnLoading: false,
        },
        fromHeight: window.innerHeight - 100,
        direction: 'rtl',
        formData: {
          parent: [],
          templateId: undefined,
          imgUrl: null,
          status: true,
          linkUrl: undefined,
          title: undefined,
          subTitle: undefined,
          number: undefined,
          enTitle: undefined,
          keyWord: undefined,
          summary: undefined,
          content: '',
        },
        rules: {
          parent: [
            {
              required: true,
              type: 'array',
              message: '请至少选择一个所属上级',
              trigger: 'change',
            },
          ],
          templateId: [
            {
              required: true,
              message: '请选择栏目模板',
              trigger: 'change',
            },
          ],
          linkUrl: [],
          title: [
            {
              required: true,
              message: '请输入栏目名称',
              trigger: 'blur',
            },
          ],
          subTitle: [],
          number: [
            {
              required: true,
              message: '请输入栏目编号',
              trigger: 'blur',
            },
          ],
          enTitle: [],
          keyWord: [],
          summary: [],
          content: [],
        },
        imgUrlAction: 'https://jsonplaceholder.typicode.com/posts/',
        imgUrlfileList: [],
        parentIdOptions: [],
        templateIdOptions: [],
        parentProps: {
          multiple: false,
          checkStrictly: true,
          expandTrigger: 'hover',
          label: 'label',
          value: 'value',
          children: 'children',
        },
      }
    },
    created() {
      //this.initTree()
    },
    mounted() {
      tinymce.init({})
    },
    methods: {
      async initTree() {
        const t = await getList()
        let _tree = [{ id: '1', value: '0', label: '根目录', parentId: '0' }]
        t.data.some((m) => {
          _tree.push({
            id: m.id,
            value: m.id,
            label: m.title,
            parentId: m.parentId,
          })
        })
        this.templateIdOptions = []
        this.parentIdOptions = changeTree(_tree)
        const _temp = await getTempList()
        _temp.data.items.some((m) => {
          this.templateIdOptions.push({ label: m.name, value: m.id })
        })
      },
      close() {
        this.drawer.open = false
        this.$refs['elForm'].resetFields()
      },
      imgUrlBeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      submitForm() {
        this.$refs['elForm'].validate(async (valid) => {
          if (!valid) return

          this.drawer.btnLoading = true
          const _parentList = this.formData.parent.join(',')
          this.formData.parentId = this.formData.parent.pop()
          this.formData.parentIdList = _parentList
          let tipName = '添加成功'
          let res = null
          if (!this.formData.id) {
            this.formData.id = undefined
            res = await add(this.formData)
          } else {
            tipName = '修改成功'
            res = await update(this.formData)
          }
          this.drawer.btnLoading = false
          if (res.code == 200) {
            this.close()
            this.$emit('complete')
            this.$notify({
              message: tipName,
              type: 'success',
            })
          } else {
            this.$notify({
              message: message,
              type: 'error',
            })
          }
        })
      },
      resetForm() {
        this.$refs['elForm'].resetFields()
      },
      handleAdd() {
        this.formData.id = undefined
        this.drawer.open = true
        this.drawer.title = '添加栏目'
        this.initTree()
      },
      handelModify(record) {
        this.initTree()
        record.parent = []
        var str = record.parentIdList.split(',')
        str.forEach(function (item, i) {
          if (item != record.id && item) {
            record.parent.push(item)
          }
          if (record.parentId == '0' && item) {
            record.parent.push('0')
          }
        })
        this.drawer.open = true
        this.drawer.title = '编辑栏目'
        this.$nextTick(() => {
          this.formData = deepClone(record)
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then((_) => {
            this.$refs['elForm'].resetFields()
            done()
          })
          .catch((_) => {})
      },
    },
  }
</script>
<style>
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .column-form {
    padding-right: 20px;
  }
</style>
